import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayOpenAuthAppauthInviteCreateModel;
import com.alipay.api.request.AlipayOpenAgentSignstatusQueryRequest;
import com.alipay.api.request.AlipayOpenAuthAppauthInviteCreateRequest;
import com.alipay.api.response.AlipayOpenAgentSignstatusQueryResponse;
import com.alipay.api.response.AlipayOpenAuthAppauthInviteCreateResponse;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.enums.v3.PayScoreApiEnum;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.partnerpayments.jsapi.JsapiService;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Amount;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Payer;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import top.lidee.lideeApplication;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
@SpringBootTest(classes = lideeApplication.class)
@Slf4j
public class YufubaoTest2 {



    @Resource
    private WxMaService wxMaService;

//    @Autowired
//    private AliPayResource aliPayResource;



    /**
     * 图片下载
     * */
    @Test
    public void test6()  {
        try {
            download("https://www.baidu.com/img/bd_logo1.png", "C:\\Users\\30756\\Desktop\\code\\qrcod2.png");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static void download(String urlString, String filename)
            throws Exception {
        URL url = new URL(urlString);// 构造URL
        URLConnection con = url.openConnection();// 打开连接
        InputStream is = con.getInputStream();// 输入流
        String code = con.getHeaderField("Content-Encoding");
        if ((null != code) && code.equals("gzip")) {
            GZIPInputStream gis = new GZIPInputStream(is);
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            OutputStream os = new FileOutputStream(filename);
            // 开始读取
            while ((len = gis.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            gis.close();
            os.close();
            is.close();
        } else {
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            OutputStream os = new FileOutputStream(filename);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
        }
    }


    /** 商户号 */
    public static String merchantId = "1684161885";
    /** 商户API私钥路径 */
    public static String privateKeyPath = "C:\\Users\\30756\\Desktop\\code\\yufubaosoft2\\lidee-application\\src\\main\\resources\\apiclient_key.pem";
    /** 商户证书序列号 */
    public static String merchantSerialNumber = "4BAD83B252933AD7B1FE0D933CCB573F6F46123A";
    /** 商户APIV3密钥 */
    public static String apiV3Key = "wxapi3beijingyufubao202410141652";
    /**
     * wechatpay SDK
     * */
    @Test
    public void test1(){
// 使用自动更新平台证书的RSA配置
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        // 构建service
//        NativePayService service = new NativePayService.Builder().config(config).build();//native
        JsapiService service = new JsapiService.Builder().config(config).build();//jsapi
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(100);
        request.setAmount(amount);
        request.setSpAppid("wxc6e36f068ca78b45");
        request.setSpMchid("1684161885");
        request.setSubMchid("1695344941");
        request.setDescription("测试商品标题");
        request.setNotifyUrl("https://notify_url");
        request.setOutTradeNo("12333445555tt66");
        Payer payer = new Payer();
        payer.setSpOpenid("ol3KO7aUeMCu3FPrznfF3gvZfrvo");
        request.setPayer(payer);
        // 调用下单方法，得到应答
        PrepayResponse response = service.prepay(request);

        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
//        System.out.println(response.getCodeUrl());
        System.out.println(response.getPrepayId());//jsapi 返回值

    }


    @Autowired
    private CloseableHttpClient wxPayNoSignClient;
    /**
     * 微信支付分 开通状态查询接口
     * */
    @Test
    public void test2(){
        String url="https://api.mch.weixin.qq.com/payscore/user-service-state?service_id=111&appid=wxc6e36f068ca78b45&openid=ol3KO7aUeMCu3FPrznfF3gvZfrvo";
        HttpGet httpClient = new HttpGet(url);
        httpClient.setHeader("Accept", "application/json");
        //完成签名并执行请求
        try (CloseableHttpResponse response = wxPayNoSignClient.execute(httpClient)) {
            System.out.println("微信支付分状态查询,返回code = " + response.getStatusLine().getStatusCode() + ",返回body = " + EntityUtils.toString(response.getEntity()));
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 微信支付分 创建订单
     * */
    @Test
    public void test3(){
        Map<String, Object> map = new HashMap<>();
//        map.put("sp_appid",wxPayApiConfig.getAppId());
//        map.put("sp_mchid",wxPayApiConfig.getMchId());//商户
//        map.put("sub_mchid",weChatInputPieceLog.getSubMchid());//二级商户  不归属报错：受理关系不存在
//        map.put("description",param.getDes());
//        map.put("out_trade_no","XXXXXXXXXX");
//        map.put("notify_url",wxPayApiConfig.getDomain() + CALL_BACK_URL);
//        Map<String,Object> amountMap=new HashMap<>();
//        amountMap.put("total","XXXXXXXXXXX");
//        amountMap.put("currency","CNY");
//        map.put("amount",amountMap);
//        Map<String,Object> payerMap=new HashMap<>();
//        payerMap.put("sp_openid",getOpenId(param.getCode()));
//        map.put("payer",payerMap);


        String jsonMapStr = JSON.toJSONString(map);
        HttpPost httpClient = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi");
        StringEntity entity = new StringEntity(jsonMapStr, "utf-8");
        entity.setContentType("application/json");
        httpClient.setEntity(entity);
        httpClient.setHeader("Accept", "application/json");




        //完成签名并执行请求
        try (CloseableHttpResponse response = wxPayNoSignClient.execute(httpClient)) {
            System.out.println("微信支付分状态查询,返回code = " + response.getStatusLine().getStatusCode() + ",返回body = " + EntityUtils.toString(response.getEntity()));
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

//    public AlipayClient getAlipayClient() {
//        AlipayClient alipayClient = new DefaultAlipayClient(aliPayResource.getGatewayUrl(), aliPayResource.getAppId(), aliPayResource.getMerchantPrivateKey(), "json", aliPayResource.getCharset(), aliPayResource.getAlipayPublicKey(), aliPayResource.getSignType());
//        return alipayClient;
//    }

    @Test
    public void test4() throws AlipayApiException {
//        AlipayClient alipayClient = getAlipayClient();
//        AlipayOpenAuthAppauthInviteCreateRequest request = new AlipayOpenAuthAppauthInviteCreateRequest();
//        AlipayOpenAuthAppauthInviteCreateModel model = new AlipayOpenAuthAppauthInviteCreateModel();
////        model.setAuthAppId(aliPayResource.getAppId());
////        model.setRedirectUrl(aliPayResource.getNotifyUrl());
//        request.setBizModel(model);
//        AlipayOpenAuthAppauthInviteCreateResponse response = alipayClient.execute(request);
//        JSONObject parseObject = JSONObject.parseObject(response.getBody());
//        System.out.println("================="+parseObject+"=============");
//        if(response.isSuccess()){
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//        }
    }

    @Test
    public void test5() throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        AlipayOpenAgentSignstatusQueryRequest request = new AlipayOpenAgentSignstatusQueryRequest();
        request.setBizContent("{" +
                "  \"pid\":\"支付宝账号：2088123451234543或手机号：13811111111或邮箱：123@xxx.com\"," +
                "  \"product_codes\":[" +
                "    \"I1011000100000000001\"" +
                "  ]" +
                "}");
        AlipayOpenAgentSignstatusQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }


}
